package com.ysh.service;

import java.io.File;
import java.io.FileOutputStream;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import org.apache.log4j.Logger;

import com.adobe.demo.Consultant;
import com.ysh.gsm.TDProject;


public class FileUtils {
	
	private static Logger logger = Logger.getLogger(FileUtils.class);

	public String doUpload(byte[] bytes, String fileName) throws Exception {
		fileName = System.getProperty("java.io.tmpdir") + "/" + fileName;
		File f = new File(fileName);
		FileOutputStream fos = new FileOutputStream(f);
		fos.write(bytes);
		fos.close();
		return "success";
	}
	public void saveProject(TDProject project)throws Exception{
		
		EntityManagerFactory entityManagerFactory  = PersistenceManager.getInstance().getEntityManagerFactory();
		EntityManager em = entityManagerFactory.createEntityManager();
		project.setDate(new Timestamp(new Date().getTime()));
		
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		try {
			em.merge(project);
			tx.commit();
			logger.info("add new project " +project.getName()+ " success.");
		} catch (Exception e) {
			logger.error("** Error: " + e.getMessage());
			tx.rollback();
			throw new Exception(e.getMessage());
		} finally {
			logger.info("** Closing Entity Manager.");
			em.close();
		}
		
	}
	public List<TDProject> getProjects(){
		
		EntityManagerFactory entityManagerFactory  = PersistenceManager.getInstance().getEntityManagerFactory();
		EntityManager em = entityManagerFactory.createEntityManager();
		
		Query findAllQuery = em.createNamedQuery("project.findAll");
		
		List<TDProject> result=findAllQuery.getResultList();
		
		return result;
		
		
		
	}
	public void deleteProject(TDProject project){
		
		EntityManagerFactory entityManagerFactory  = PersistenceManager.getInstance().getEntityManagerFactory();
		EntityManager em = entityManagerFactory.createEntityManager();
		Query q = em.createNamedQuery("project.byId");
		q.setParameter("id", project.getId());
		TDProject pro = (TDProject) q.getSingleResult();
		if (pro != null) {
			EntityTransaction tx = em.getTransaction();
			tx.begin();
			try {
				em.remove(pro);
				tx.commit();
			} catch (Exception e) {
				logger.error("** Error: " + e.getMessage());
				tx.rollback();
			} finally {
				logger.info("** Closing Entity Manager.");
				em.close();
			}
		}
		
	}

}
